package Offer2017;

/**
 * 字符串转化为整型
 * Created by 雷文康 on 2018/1/6.
 */
public class Test49 {
    public static void main(String[] args) {
        String str="243";
        System.out.println(strToInt(str));
    }
    public static int strToInt(String str){
        if (str == null || str.length() == 0){
            return -1;
        }
        char[] ch = str.toCharArray();
        boolean minus = false;
        int i = 0;
        if (ch[0] == '+') {
            i++;
        }
        if (ch[0] == '-') {
            minus = true;
            i++;
        }
        int result = 0;
        while (i < ch.length) {
            if (ch[i] >= '0' && ch[i] <= '9') {
                int sum = (ch[i] - '0');
                for(int j = 0;j < ch.length - i - 1; j++){
                    sum = sum * 10;
                }
                result += sum;
            } else {
                return -1;
            }
            i++;
        }
        if (minus) {
            result = -result;
        }
        return result;
    }
}
